<!DOCTYPE html>
<html>
<body>
<style>
.r{background-color:red;}
</style>
<p>Click the button to replace "blue" with "red" in the paragraph below:</p>

<p id="demo">
 I d like to create a String.replaceAll() method in JavaScript and I m thinking that using a RegEx would be most terse way to do it. However, I can't figure out how to pass a variable in to a RegEx. I can do this already which will replace all the instances of "B" with "A".


aaaaaaa[[[[[[[[[[[[[[[[[[[[[[[[[[[[aaaa[[[aaaaaaa]]]aaaa Mr Blue has a blue house and a blue car.</p>

<button onclick="myFunction()">Try it</button>
<input id="txt" value="" length="200" onkeyup="javascript:Marca()" />
<script>
function myFunction()
{
var str=document.getElementById("demo").innerHTML; 
var n=str.replace(/a/g,"<span class='r'>x</span>");
document.getElementById("demo").innerHTML=n;
}

var original = "";

function Marca(){
var str=document.getElementById("demo").innerHTML; 
if (original==""){original = str;}
str = original;
var aGrifar = document.getElementById("txt").value;

var regex = new RegExp();
var src = "\\ " + aGrifar; // don't forget to escape slashes!
src = src.replace(/\(/g,"").replace(/\)/g,"");
var mods  = "g";
regex.compile(src, mods); 


//var n=str.replace(/a/g,"<span class='r'>x</span>");
str = str.replace(/\(/g,"").replace(/\)/g,"");
var n=str.replace(regex,"<span class='r'> " + aGrifar + "</span>");
document.getElementById("demo").innerHTML=n;
}

</script>

</body>
</html>
